import os
import sys
import requests
from pathlib import Path


def upload_single_file(file_path: Path, base_dir: Path, server_url: str):
    rel_path = file_path.relative_to(base_dir).as_posix()

    files = {"files[]": (file_path.name, open(file_path, "rb"))}
    data = {
        "paths[]": rel_path,
        "batch_roots[]": file_path.name,  # 用文件名作为 commit 信息
    }

    try:
        resp = requests.post(f"{server_url}/upload", files=files, data=data)
        print(f"[{rel_path}] 状态码: {resp.status_code}")
        print("响应:", resp.text)
    finally:
        files["files[]"][1].close()


def upload_folder_each(base_dir: Path, server_url: str):
    for root, _, files in os.walk(base_dir):
        for fname in files:
            file_path = Path(root) / fname
            upload_single_file(file_path, base_dir, server_url)


if __name__ == "__main__":
    if len(sys.argv) != 3:
        print(f"用法: python {sys.argv[0]} <文件夹路径> <服务器地址>")
        print(f"示例: python {sys.argv[0]} ./mydata http://127.0.0.1:80")
        sys.exit(1)

    folder = Path(sys.argv[1]).resolve()
    server = sys.argv[2]

    if not folder.exists() or not folder.is_dir():
        print(f"目录不存在: {folder}")
        sys.exit(1)

    upload_folder_each(folder, server)
